const DB = require('../../utils/db');
const { cosDelete, cosUpload } = require('../../utils/oss');
const path = require('path');

// 文件夹名称
let ossDirectory = 'article';

module.exports = {
	list: async (title, type = 0, isHot = 0, isRecommend = 0, pageNum, pageSize) => {
		// 总条数
		let [allList] = await DB.query(`select * from t_acticle where title like '%${title}%' and if(${type}=0,1,type=${type}) and 
                  if(${isHot}=0,1,is_hot=${isHot}) and if(${isRecommend}=0,1,is_recommend=${isRecommend})`);

		let arr = [(pageNum - 1) * pageSize, pageSize];

		let newSql = `select a.id,a.likes, a.title, a.url,a.fullUrl, a.is_hot isHot, a.is_top isTop, a.is_recommend isRecommend, a.state, a.type, t.name typeName,
                              a.label, a.abstract, a.content, a.editor, a.visitors, a.comments, date_format(a.create_time,'%Y-%m-%d %H:%i:%s') createTime,
                              date_format(a.update_time,'%Y-%m-%d %H:%i:%s') updateTime from t_acticle a left join t_acticle_type t on a.type= t.id
                              where a.title like '%${title}%' and if(${type}=0,1,a.type=${type}) and if(${isHot}=0,1,a.is_hot=${isHot}) and if(${isRecommend}=0,1,a.is_recommend=${isRecommend})
                              limit ?,?`;
		let [list] = await DB.query(newSql, arr);
		return { data: list, total: allList.length };
	},
	add: async (title, editor, content, url, filename, isHot, isTop, isRecommend, state, type, abstract, label) => {
		// 上传oss
		let { Location } = await cosUpload(ossDirectory, filename);

		// oss 全路径
		let fullUrl = 'https://' + Location;

		// 新增
		await DB.query('insert into t_acticle (title, editor,content, url,fullUrl, is_hot, is_top, is_recommend, state, type, abstract,label) values(?,?,?,?,?,?,?,?,?,?,?,?)', [
			title,
			editor,
			content,
			url,
			fullUrl,
			isHot,
			isTop,
			isRecommend,
			state,
			type,
			abstract,
			label
		]);
	},
	edit: async (title, editor, content, url, filename, isHot, isTop, isRecommend, state, type, abstract, label, id) => {
		let [list] = await DB.query('select url from t_acticle where id=?', [id]);
		// 判断是否修改图片
		if (list[0].url != url) {
			// 删除oss
			await cosDelete(ossDirectory, path.basename(list[0].url));

			// 上传oss
			let { Location } = await cosUpload(ossDirectory, filename);
			// oss 全路径
			let fullUrl = 'https://' + Location;
			await DB.query(`update t_acticle set title=?, editor=?, content=?, url=?,fullUrl=?,is_hot=?,is_top=?,is_recommend=?,state=?,type=?,label=?,abstract=? where id =?`, [
				title,
				editor,
				content,
				url,
				fullUrl,
				isHot,
				isTop,
				isRecommend,
				state,
				type,
				label,
				abstract,
				id
			]);
		} else {
			await DB.query(`update t_acticle set title=?, editor=?, content=?, is_hot=?,is_top=?,is_recommend=?,state=?,type=?,label=?,abstract=? where id =?`, [
				title,
				editor,
				content,
				isHot,
				isTop,
				isRecommend,
				state,
				type,
				label,
				abstract,
				id
			]);
		}
	},
	del: async (id) => {
		let [list] = await DB.query('select * from t_acticle where id=?', [id]);

		// 删除markdown oss 图片
		let content = list[0].content;
		const regex = /\((.*?)\)/g; // 使用非贪婪模式匹配
		const matches = content.match(regex);
		if (matches) {
			// 提取小括号内的内容
			const arr = matches.map((match) => match.replace(/\(|\)/g, ''));
			Promise.all(arr.map((item) => cosDelete('markdown', path.basename(item))));
		}

		// 删除oss 图片
		await cosDelete(ossDirectory, path.basename(list[0].url));
		await DB.query('delete from t_acticle where id=?', [id]);
	},
	detail: async (id) => {
		let [list] = await DB.query(
			`select id, title, url, fullUrl, is_hot isHot, is_top isTop, is_recommend isRecommend, state, type, label, abstract, 
                            content, editor, visitors, comments, date_format(create_time,'%Y-%m-%d %H:%i:%s') createTime, 
                            date_format(update_time,'%Y-%m-%d %H:%i:%s') updateTime from t_acticle where id=?`,
			[id]
		);
		if (!list.length) throw new Error('文章ID不存在，请检查文章ID');
		return list[0];
	}
};
